<template>
	<view class="address-page">
		<view class="adress-type">
			<view @click="changeTab('cloudFunc')" :class="['type-item', activeTab==='cloudFunc'?'active':'']">
				云函数
			</view>
			<view @click="changeTab('clientDB')" :class="['type-item', activeTab==='clientDB'?'active':'']">
				ClientDB
			</view>
		</view>
		<template v-if="activeTab==='cloudFunc'">
			<view v-if="!loading && addressList.length===0" class="empty-list">
				<img class="empty-image" src="@/common/images/empty.png">
				<text class="empty-text">目前还没有收货地址</text>
				<button class="empty-add-address-btn" type="primary">添加收货地址</button>
			</view>
			<view class="address-list" v-else>
				<view class="delete-btn">
					<button @click="patchDelete" type="primary">批量删除</button>
					<button @click="patchDelete('all')" type="primary">全部删除</button>
				</view>
				<view class="address-item" v-for="item in addressList" :key="item._id">
					<view class="address-info" @click="doSelect(item)">
						<icon class="select-icon" size=18 type="success" v-if="item.isSelected"></icon>
						<view class="address-con">
							<view class="address-user">
								<view class="user-name">{{item.userName}}</view>
								<view class="user-phone">{{item.phone}}</view>
							</view>
							<view class="address">
								{{item.address}}
							</view>
						</view>
					</view>
					<view class="address-play">
						<view class="play-default">
							<switch :checked="item.isDefault" disabled @click="doDefault(item)"
								style="transform: scale(0.5);" /><text
								:class="['default-text',item.isDefault?'is-default':'']">{{item.isDefault?'已设为默认':'设置为默认'}}</text>
						</view>
						<view class="play-btn">
							<view class="btn" @click="deleteAddress(item)">删除</view>
							<view class="btn" @click="editAddress(item)">编辑</view>
						</view>
					</view>
				</view>
				<!-- <button :disabled="!hasMore" type="warn" @click="getNextPage">下一页</button> -->
			</view>
		</template>
		<template v-else>
			<unicloud-db ref="udb" v-slot:default="{data, loading, error, options}" collection="address_list">
				<view v-if="error">{{error.message}}</view>
				<view class="address-list" v-else>
					<view class="address-item" v-for="item in data" :key="item._id">
						<view class="address-info" @click="doSelect(item)">
							<icon class="select-icon" size=18 type="success" v-if="item.isSelected"></icon>
							<view class="address-con">
								<view class="address-user">
									<view class="user-name">{{item.userName}}</view>
									<view class="user-phone">{{item.phone}}</view>
								</view>
								<view class="address">
									{{item.address}}
								</view>
							</view>
						</view>
						<view class="address-play">
							<view class="play-default">
								<switch :checked="item.isDefault" disabled @click="doDefault(item)"
									style="transform: scale(0.5);" /><text
									:class="['default-text',item.isDefault?'is-default':'']">{{item.isDefault?'已设为默认':'设置为默认'}}</text>
							</view>
							<view class="play-btn">
								<view class="btn" @click="deleteAddressByClientDb(item)">删除</view>
								<view class="btn" @click="editAddress(item)">编辑</view>
							</view>
						</view>
					</view>
					<!-- <button :disabled="!hasMore" type="warn" @click="getNextPage">下一页</button> -->
				</view>
			</unicloud-db>
		</template>
		<view class="footer">
			<button @click="addAddress" class="add-btn" type="primary"><uni-icons style="margin-right: 10rpx;"
					color="#fff" type="plusempty"></uni-icons>添加收货地址</button>
		</view>
		<address-popup :type='activeTab' ref="addressPopup" @success-callback="getAddressList"></address-popup>
	</view>
</template>

<script>
	const addressObj = uniCloud.importObject('address')
	export default {
		data() {
			return {
				activeTab: 'cloudFunc',
				loading: true,
				selectedAddress:[],
				addressList: [],
				addressObj: null,
				pageNum: 1,
				pageSize: 10,
				hasMore: true
			}
		},
		onLoad() {
			if (this.activeTab === 'cloudFunc') {
				this.getAddressList()
			}
		},
		mounted() {},
		methods: {
			async patchDelete(type) {
				//this.selectedAddress
				let result
				if(type==='all') {
					result = await addressObj.deleteData({type: 'all'})
				} else {
					result = await addressObj.deleteData({ids: this.selectedAddress})
				}
				uni.showToast({
					title:'删除成功',
					icon:'success'
				})
				this.getAddressList()
			},
			changeTab(type) {
				this.activeTab = type
				if (type === 'cloudFunc') {
					this.getAddressList()
				}
			},
			//获取下一页数据
			getNextPage() {
				this.pageNum = this.pageNum + 1
				this.getAddressList()
			},

			//添加地址
			addAddress() {
				this.$refs['addressPopup'].childOpen()
			},
			deleteAddressByClientDb(item) {
				this.$refs.udb.remove(item._id, {
					totalTitle: '删除成功',
					success: (res) => { // 新增成功后的回调
						this.$refs.udb.refresh()
						this.getAddressList()
					}
				})
			},
			async deleteAddress(data) {
				const result = await addressObj.deleteData({
					_id: data._id
				})
				if (result.code === 200) {
					this.getAddressList()
				}
			},
			//编辑地址
			editAddress(item) {
				this.$refs['addressPopup'].childOpen(item._id)
			},
			//操作选中
			doSelect(item) {
				item.isSelected = !item.isSelected
				if(item.isSelected) {
					this.selectedAddress.push(item._id)
				} else {
					let index = this.selectedAddress.findIndex(addressItem => addressItem === item._id)
					this.selectedAddress.splice(index,1)
				}
			},
			doDefault(item) {
				let defaultAddress = this.addressList.find(addressItem => addressItem.isDefault)
				if (!defaultAddress) {
					item.isDefault = !item.isDefault
				}
				if (defaultAddress && !item.isDefault) {
					uni.showToast({
						title: '已有默认地址',
						icon: 'error'
					})
					return false
				}
				if (defaultAddress && item._id === defaultAddress._id) {
					item.isDefault = !item.isDefault
				}
				// let num = this.addressList.filter(item => item.isDefault)
				// console.log(num)
				// if(flag) {
				// 	if(!item.isDefault) {
				// 		uni.showToast({
				// 			title:'已有默认地址',
				// 			icon: 'error'
				// 		})
				// 		return
				// 	}
				// }
			},
			async getAddressList() {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				let res = await addressObj.getData({
					pageSize: this.pageSize,
					pageNum: this.pageNum
				})
				this.loading = false
				uni.hideLoading()
				this.addressList = res.data.map(item => ({
					...item,
					isSelected: false,
					isDefault: item.isDefault || false
				}))
				this.hasMore = res.hasMore
				console.log(res)
			},
		}
	}
</script>

<style lang="scss">
	.address-page {
		position: relative;
		height: 100%;

		.adress-type {
			display: flex;
			align-items: center;

			.type-item {
				height: 80rpx;
				line-height: 80rpx;
				flex: 1;
				text-align: center;

				&.active {
					color: #1aad19;
				}
			}
		}

		.empty-list {
			display: flex;
			align-items: center;
			flex-direction: column;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);

			.empty-image {
				width: 300rpx;
				height: 250rpx;
			}

			.empty-text {
				margin: 20rpx 0;
				color: #ccc;
			}

			.empty-add-address-btn {
				border-radius: 46rpx;
			}
		}

		.address-list {
			// padding-top: 20rpx;
			padding-bottom: 128rpx;
			.delete-btn{
				display: flex;
				align-items: center;
			}
			.address-item {
				background: #fff;
				margin-bottom: 20rpx;
				padding: 20rpx;

				.address-info {
					display: flex;
					align-items: center;
					padding-bottom: 20rpx;
					border-bottom: 1px solid #ccc;

					.select-icon {
						display: inline-block;
						margin-right: 15rpx;
					}

					.address-con {
						flex: 1;
						width: 0;

						.address-user {
							display: flex;
							align-items: center;

							.user-phone {
								margin-left: 200rpx;
							}
						}
					}

					.address {
						color: #999;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}
				}

				.address-play {
					padding-top: 20rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;

					.default-text {
						margin-left: -18rpx;
						display: inline-block;

						&.is-default {
							color: #1aad19;
						}
					}

					.play-btn {
						color: #ddd;
						display: flex;
						align-items: center;

						.btn {
							margin-left: 15rpx;
						}
					}

					.play-default {
						display: flex;
						align-items: center;
					}
				}
			}
		}

		.footer {
			background: #fff;
			position: fixed;
			bottom: 0;
			width: 100%;
			padding: 20rpx 0 30rpx;

			.add-btn {
				margin: 0 auto;
				width: 90%;
				border-radius: 46rpx;
			}
		}

	}
</style>